package com.hanxiaozhang.no3algorithm;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 * 喵星人的计算机采用的是三进制数表示，三个数字符号分别是：0、1、2现需要写一个程序实现对输入的两个三进制数进行相加。
 * 两个三进制数以字符串的形式传入
 * 示例
 * 输入：nums1="121",num2="1212"
 * 输出："2110"
 *
 * @author hanxinghua
 * @create 2022/7/3
 * @since 1.0.0
 */
public class No4Ternary {


    public static void main(String[] args) {

        System.out.println(ternary("121", "1212"));

    }


    public static String ternary(String num1, String num2) {
        String[] str1 = num1.split("");
        String[] str2 = num2.split("");
        String[] strA = null, strB = null;
        Integer lenA = 0, lenB = 0;
        if (str1.length > str1.length) {
            strA = str1;
            lenA = str1.length;
            strB = str2;
            lenB = str2.length;
        } else {
            strA = str2;
            lenA = str2.length;
            strB = str1;
            lenB = str1.length;
        }
        int count = 0, jinwei = 0, sum = 0;
        String[] str = new String[lenA + 1];

        // 注意循环条件  int i = 长度-1 ; i >= 0 -> 大于等于0，才可以循环到0
        for (int i = lenA - 1; i >= 0; i--) {
            if ((lenB - 1 - count) >= 0) {
                sum = Integer.parseInt(strA[i]) + Integer.parseInt(strB[lenB - 1 - count]) + jinwei;

            } else {
                sum = Integer.parseInt(strA[i]) + jinwei;
            }

            if (sum < 3) {
                jinwei = 0;
                str[count] = String.valueOf(sum);
            } else if (sum == 3) {
                jinwei = 1;
                str[count] = "0";
            } else if (sum == 4) {
                jinwei = 1;
                str[count] = "1";
            }
            count++;
        }
        if (jinwei > 0) {
            str[count] = String.valueOf(jinwei);
        }

        String target = "";
        for (int i = lenA; i >= 0; i--) {
            if (null != str[i]) {
                target += str[i];
            }
        }


        return target;
    }


}
